﻿var listImage = [];

$(document).ready(function () {
    $("body").css("background", "none");
    setTimeout(function () {
        $(".lnkImage").click(function () {
            var imgId = $(this).find("img").attr("imageid");
            var index = $(this).find("img").attr("index");

            if ($(".selected").parent().find("img").attr("imageid") == imgId) {
                return false;
            }

            loadImage(imgId, index);

            $(".selected").removeClass("selected");
            $(this).parent().find(".lnkImage").addClass("selected");
            setPosition(index);
            return false;
        });

        $(".mask").click(function () {
            $(this).parent().find(".lnkImage").click();
        });

        var imgCount = $(".lnkImage").length;

        for (var i = 0; i < imgCount; i++) {
            listImage.push('');
        }

        $(".lnkImage").first().click();
    }, 500);

    $("#previous, #next").click(function () {
        var tmp = 1;
        if ($(this).attr("id") == "previous") {
            tmp = -1;
        }
        var length = $(".lnkImage").length;
        var index = parseInt($(".selected").parent().find("img").attr("index")) + tmp - 1;
        index = (index + length) % length + 1;
        $("img[index=" + index + "]").parent().click();
    });

    $(window).bind("keydown", function (e) {
        if (e.keyCode == 37) {          // left arrow
            $("#previous").click();
        }
        else if (e.keyCode == 39) {     // right arrow
            $("#next").click();
        }
    });

    $("#groupId").attr("tabindex", -1).focus();
});

function setPosition(index) {
    var lst = $("#listThumnal");
    var width = $(".nav").width();
    var itemWidth = lst.find("li").first().outerWidth();
    var left = width / 2 - itemWidth;
    left -= (itemWidth * (index - 1));
    $(lst).css("left", left);
}

function loadImage(imageIndex, index) {
    if (listImage[imageIndex] != null && listImage[imageIndex] != '') {
        $('#image').attr("src", listImage[imageIndex]);
        return false;
    }

    var action = "/Master/GetOriginalImageUrl";
    var groupId = $("#groupId").val();
    var subGroupId = $("#subGroupId").val();
    var productId = $("#productId").val();
    var param = "?groupId=" + groupId + "&subGroupId=" + subGroupId +
        "&productId=" + productId + "&imageIndex=" + imageIndex + "&index=" + index;

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            $('#image').attr("src", this.responseText);
            listImage[imageIndex] = this.responseText;
        }
    }
    xhr.open('GET', action + param);
    xhr.responseType = 'text';
    xhr.send();
    
    return false;
}